<template>
  <el-dialog
      :title="isEdit ? '编辑社区' : '添加社区'"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="社区名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入社区名称"/>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入地址"/>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, computed, watch} from 'vue'
import {ElMessage} from 'element-plus'
import type {FormInstance} from 'element-plus'
import type {Community} from '@/types/community'
import type {Elder} from '@/types/elder'
import type {Child} from '@/types/child'
import {addCommunity, updateCommunity} from '@/api/community'

const props = defineProps<{
  modelValue: boolean
  community?: Community
  isEdit: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const formRef = ref<FormInstance>()
const loading = ref(false)

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = ref({
  id: 0,
  name: '',
  address: '',
  phone: '',
  doctors: [],
  elders: [] as Elder[],
  children: [] as Child[]
})

const rules = {
  name: [{required: true, message: '请输入社区名称', trigger: 'blur'}],
  address: [{required: true, message: '请输入地址', trigger: 'blur'}],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
}

// 监听 community 属性变化，更新表单数据
watch(
    () => props.community,
    (newVal) => {
      if (newVal) {
        form.value = {
          id: newVal.id,
          name: newVal.name,
          address: newVal.address,
          phone: newVal.phone,
          doctors: newVal.doctors,
          elders: newVal.elders,
          children: newVal.children
        }
      } else {
        // 重置表单
        form.value = {
          id: 0,
          name: '',
          address: '',
          phone: '',
          doctors: [],
          elders: [],
          children: []
        }
      }
    },
    {immediate: true}
)

// 监听对话框显示状态，重置表单
watch(
    () => dialogVisible.value,
    (newVal) => {
      if (!newVal) {
        handleClose()
      } else if (props.community) {
        // 当对话框打开且有 community 数据时，更新表单
        form.value = {
          id: props.community.id,
          name: props.community.name,
          address: props.community.address,
          phone: props.community.phone,
          doctors: props.community.doctors,
          elders: props.community.elders,
          children: props.community.children
        }
      }
    }
)

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  form.value = {
    id: 0,
    name: '',
    address: '',
    phone: '',
    doctors: [],
    elders: [],
    children: []
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (props.isEdit) {
      await updateCommunity(form.value)
    } else {
      await addCommunity(form.value)
    }

    ElMessage.success(props.isEdit ? '更新成功' : '添加成功')
    emit('success')
    dialogVisible.value = false
  } catch (error) {
    console.error('表单提交失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 